package com.mohunhun.controller;

import com.mohunhun.common.AppResult;
import com.mohunhun.common.ResultCode;
import com.mohunhun.config.AppConfig;
import com.mohunhun.model.Article;
import com.mohunhun.model.ArticleReply;
import com.mohunhun.model.User;
import com.mohunhun.services.IArticleReplyService;
import com.mohunhun.services.IArticleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Slf4j
@Tag(name = "回复接口")
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IArticleReplyService articleReplyService;


    @Operation(summary = "回复帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @Parameter(description = "帖子ID") @RequestParam("articleId") @NonNull Long articleId,
                            @Parameter(description = "回复内容") @RequestParam("content") @NonNull String content) {
        HttpSession session = request.getSession(false);


        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }


        Article article = articleService.selectById(articleId);
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        if (article.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setPostUserId(user.getId());
        articleReply.setContent(content);

        articleReplyService.create(articleReply);


        return AppResult.success();
    }


    @Operation(summary = "回复帖子")
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId(
            @Parameter(description = "帖子ID") @RequestParam("articleId") @NonNull Long articleId) {
        Article article = articleService.selectById(articleId);
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }


        if (article.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        List<ArticleReply> result = articleReplyService.selectByArticleId(articleId);

        return AppResult.success(result);
    }

}
